package top.yehot.cmmu.core.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Objects;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;

/**
 * 序列化工具类
 * 
 * @author lquan
 * @date 2022-9-9 20:59:32
 */
public class JSerializeUtil {

	/**
	 * 序列化<br>
	 * 如果 object 是对象，请实现接口 {@link java.io.Serializable}
	 */
	public static String serialize(Object object) {
		if (Objects.isNull(object)) {
			return null;
		}
		
		try(
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos  = new ObjectOutputStream(baos);
		) {
			oos.writeObject(object);
			return Base64.encode(baos.toByteArray());
		} catch (Exception e) {
			throw new RuntimeException("序列化失败", e);
		}
	}
	
	/**
	 * 反序列化
	 */
	public static Object deserialize(String str) {
		if (StrUtil.isBlankIfStr(str)) {
			return str;
		}
		
		try (
			ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(str));
			ObjectInputStream ois = new ObjectInputStream(bais);
		) {
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException("反序列化失败", e);
		}
	}
}
